/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：ViewScreen.java <br>
 * 创建时间：2013-8-5 下午1:43:22 <br>
 * 所属项目：GmudEX <br>
 * @author 12548 <br>
 */
package lostland.gmud.exv2.battle.netbattle;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;

import lostland.general.network.GmudHttp;
import lostland.general.network.GmudRequestListener;
import lostland.general.network.GmudRestUrl;
import lostland.gmud.exv2.Assets;
import lostland.gmud.exv2.FontSize;
import lostland.gmud.exv2.Gmud;
import lostland.gmud.exv2.battle.BattleScreen;
import lostland.gmud.exv2.battle.BattleStateInfo;
import lostland.gmud.exv2.battle.ControlScreen;
import lostland.gmud.exv2.battle.proc.holder.BattleHolder;
import lostland.gmud.exv2.blgframework.CScreen;
import lostland.gmud.exv2.blgframework.impl.BLGGraphics;
import lostland.gmud.exv2.ui.NotificationScreen;

/**
 * 类名：ViewScreen <br>
 * 说明：显示屏
 *
 * @author 12548
 */
public class ClientViewScreen extends CScreen {

	int hit = 0;

	private String str;

	AtomicInteger emptys = new AtomicInteger(0);

	public static final float LAST_TIME = 1.4f;
	float time = 0;

	volatile boolean posting = false;

	final Stack<JSONObject> ss = new Stack<>();


	public ClientViewScreen() {
		super();
		str = "正在接收数据......";
		time = 0;
//		BasicScreen.recheck();
	}


	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#update(float)
	 */
	@Override
	public void update(float deltaTime) {
		if (posting) return;
		if (this != getGame().getCurrentScreen()) return;

		time += deltaTime;
		if (time >= LAST_TIME) {
			time = 0;

			if (BattleScreen.getInstance().getBsi().client_sp <= 0) {
				BattleScreen.getInstance().holder.battle_stat = BattleHolder.BATTLE_PLAYER2_WIN;
				BattleScreen.getInstance().removeFromGame();
				removeFromGame();
				return;
			} else if (BattleScreen.getInstance().getBsi().host_sp <= 0) {
				BattleScreen.getInstance().holder.battle_stat = BattleHolder.BATTLE_PLAYER1_WIN;
				BattleScreen.getInstance().removeFromGame();
				removeFromGame();
				return;
			}

			if (ss.empty()) {
				query();
			} else {
				JSONObject state = ss.pop();

				try {
					int msgtype = state.getInt("type");
					if (msgtype == 3) {
						int result = state.getInt("numtag");

						if (result == 1) {
							BattleScreen.getInstance().holder.battle_stat = BattleHolder.BATTLE_PLAYER2_WIN;
							BattleScreen.getInstance().removeFromGame();
							removeFromGame();
							return;
						} else if (result == 2) {
							BattleScreen.getInstance().holder.battle_stat = BattleHolder.BATTLE_PLAYER1_WIN;
							BattleScreen.getInstance().removeFromGame();
							removeFromGame();
							return;
						} else {
							getGame().popToRootScreen();
							new NotificationScreen("战斗被中止！！！").pushToGame();
							return;
						}

					} else {
						str = state.getString("msg");
						hit = state.getInt("numtag");
						try {
							BattleStateInfo bsi = new Gson().fromJson(
									state.getJSONObject("tag").toString(),
									BattleStateInfo.class
							);
							BattleScreen.getInstance().setBsi(bsi);

							if (BattleScreen.getInstance().getBsi().client_sp <= 0) {
								BattleScreen.getInstance().holder.battle_stat = BattleHolder.BATTLE_PLAYER2_WIN;
								BattleScreen.getInstance().removeFromGame();
								removeFromGame();
								return;
							} else if (BattleScreen.getInstance().getBsi().host_sp <= 0) {
								BattleScreen.getInstance().holder.battle_stat = BattleHolder.BATTLE_PLAYER1_WIN;
								BattleScreen.getInstance().removeFromGame();
								removeFromGame();
								return;
							}


						} catch (JsonSyntaxException e) {
							if (Gmud.DEBUG) {
								Logger.e("BSI JSON PARSE ERROR!");
								e.printStackTrace();
							}
						}
						if (hit == 3) {
							hit = 0;
							new ControlScreen().pushToGame();
						} else if (hit == 1) {
							hit = 2;
						} else if (hit == 2) {
							hit = 1;
						}
					}


				} catch (JSONException e) {
					getGame().popToRootScreen();
					new NotificationScreen("数据错误！！").pushToGame();
				}

			}
		}

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#present(float)
	 */
	@Override
	public void present(float deltaTime) {
		BattleScreen.getInstance().present(deltaTime);
		BLGGraphics g = (BLGGraphics) getGame().getGraphics();
		g.drawRect(64, 98, 192, 96, Gmud.getBgColor());
		g.drawText(str, 64, 98, FontSize.FT_16PX, 190);
		if (hit == 1) {
			g.drawPixmap(Assets.boom, 32 * 7 + 10, 42);
		} else if (hit == 2) {
			g.drawPixmap(Assets.boom, 74, 42);
		}
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#pause()
	 */
	@Override
	public void pause() {

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#resume()
	 */
	@Override
	public void resume() {

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#dispose()
	 */
	@Override
	public void dispose() {

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#isStable()
	 */
	@Override
	public boolean isStable() {
		return true;
	}


	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#pushToGame()
	 */
	@Override
	public void pushToGame() {
		super.pushToGame();
	}

	public void query() {
		posting = true;

		RequestParams rp = GmudHttp.initBattleParams();
		rp.addBodyParameter("idstamp", BattleScreen.getInstance().idstamp + "");

		new GmudHttp().postBackground(GmudRestUrl.ClientGetMsg, rp, new GmudRequestListener() {

			@Override
			public void onSucc(ResponseInfo<String> info) {
				JSONObject jo;
				try {
					jo = new JSONObject(info.result);
					String s = jo.getString(GmudHttp.KEY_STATE);

					if (s.equals(GmudHttp.STATE_ERROR)) {
						getGame().popToRootScreen();
						new NotificationScreen("服务器错误！！").pushToGame();
					} else if (s.equals(GmudHttp.STATE_OK)) {

						BattleScreen.getInstance().idstamp = jo.getInt("idstamp");

						JSONArray jsonArray = jo.getJSONArray("msg");
						for (int i = 0; i < jsonArray.length(); i++) {
							ss.push(jsonArray.getJSONObject(i));
						}
						posting = false;

					} else if (s.equals(GmudHttp.STATE_EMPTY)) {
						posting = false;
					} else {
						getGame().popToRootScreen();
						new NotificationScreen("发生了未知错误！！").pushToGame();
					}
				} catch (JSONException e) {
					if (Gmud.DEBUG) {
						e.printStackTrace();
					}

					getGame().popToRootScreen();
					new NotificationScreen("发生了未知错误！！").pushToGame();
				}
			}

			@Override
			public void onFail(HttpException error, String msg) {
				getGame().popToRootScreen();
				new NotificationScreen("网络错误！").pushToGame();
			}
		});
	}

}
